package com.eightywork.life.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import com.eightywork.life.R;

import com.eightywork.life.activity.PmListActivity.PmListTask;
import com.eightywork.life.adapter.PmListAdapter;
import com.eightywork.life.adapter.ReplyListAdapter;
import com.eightywork.life.fragment.CommunityFragment;
import com.eightywork.life.fragment.SpaceFragment;
import com.eightywork.life.image.MyImageGetter;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.imageCache.ImageLoader.onLoadingFinishListener;
import com.eightywork.life.model.Comment;
import com.eightywork.life.model.Community;
import com.eightywork.life.receiver.MyReceiver;
import com.eightywork.life.service.BaseService;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.AndroidUtil;
import com.eightywork.life.util.FuncUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.util.PhotoUtil;
import com.eightywork.life.util.UIUtil;
import com.eightywork.life.util.Util;
import com.eightywork.life.widget.FooterView;
import com.eightywork.life.widget.MyListView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler.Callback;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;

public class ContentActivity extends BaseActivity implements OnClickListener, Callback {
	private MyListView listView;
	private ImageButton returnButton, forwardButton, goodButton;
	private Button commentButton;
	private ReplyListAdapter adapter;
	private List<Comment> coList;
	private LayoutInflater inflater;
	private EditText editText;
	private Community community;
	private TextView name, title, content, time, showgood;
	private ImageView avatar, verifyType;
	private ImageLoader imageLoader;
	private MyImageGetter getter;
	private final int[] imagesID = { R.id.image0, R.id.image1, R.id.image2,
			R.id.image3, R.id.image4, R.id.image5 };
	private Dialog dialog;
	private AsyncTask task, comment, good, detail;
	private int page = 1, position, flag = 0;
	private String idtype, person;
//	private ViewGroup footView;
	private FooterView footerView;
	private boolean isLoading, isAppend, isReply, isReplyList;
	private String id, pushType = "";
	private boolean  isFromReceive, isFromNotice;
	private long count;
	private IWXAPI api;
	private static final String WXAPP_ID = "wxcefc86293a109c7a";
	private static final int THUMB_SIZE = 150;
	private PopupWindow mPopupWindow;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_content);
		ShareSDK.initSDK(this);
		regToWx();
		initView();
		initData();
	}
	private void regToWx() {
		api = WXAPIFactory.createWXAPI(this, WXAPP_ID, true);
		api.registerApp(WXAPP_ID);
	}

	@Override
	protected void onDestroy() {
		if (task != null)
			task.cancel(true);
		if (comment != null)
			comment.cancel(true);
		if (detail != null)
			detail.cancel(true);
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}


	private void initView() {
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		listView = (MyListView) findViewById(R.id.listView1);
		returnButton = (ImageButton) findViewById(R.id.button_left);
		forwardButton = (ImageButton) findViewById(R.id.button_right);

		commentButton = (Button) findViewById(R.id.button_comment);
		editText = (EditText) findViewById(R.id.text_comment);
		View view = inflater.inflate(R.layout.content_header, null);
//		footView = (ViewGroup) getLayoutInflater().inflate(
//				R.layout.item_footer, null);
		footerView = new FooterView(this);
		footerView.hideAll();
		listView.addHeaderView(view);
		name = (TextView) findViewById(R.id.name);
		title = (TextView) findViewById(R.id.title);
		content = (TextView) findViewById(R.id.content);
		time = (TextView) findViewById(R.id.time);
		imageLoader = new ImageLoader(context);
		avatar = (ImageView) findViewById(R.id.avatar);
		getter = new MyImageGetter(context);
		showgood = (TextView) view.findViewById(R.id.showgood);
		goodButton = (ImageButton) view.findViewById(R.id.button_showgood);
		verifyType = (ImageView) view.findViewById(R.id.verify_type);
		returnButton.setOnClickListener(this);
		forwardButton.setOnClickListener(this);
		commentButton.setOnClickListener(this);
		showgood.setOnClickListener(this);
		goodButton.setOnClickListener(this);
	}
    //动态列表、通知列表、未读消息列表、推送、圈子
	private void initData() {
		isReply = getIntent().getBooleanExtra("isReply", false);
		isReplyList = getIntent().getBooleanExtra("isReplyList", false);
		isAppend = getIntent().getBooleanExtra("isAppend", false);
		position = getIntent().getIntExtra("position", -1);
		idtype = getIntent().getStringExtra("idtype");
		person = getIntent().getStringExtra("person");
		id = getIntent().getStringExtra("id");
		pushType = getIntent().getStringExtra("pushType");
		isFromReceive = getIntent().getBooleanExtra("isFromReceive", false);
		isFromNotice = getIntent().getBooleanExtra("isFromNotice", false);
		if (position != -1) {
//			if (idtype.equals("talkid")) {
//				if (person == null) {
//					community = CommunityFragment.list.get(position);
//				} else {
//					community = MessageListActivity.list.get(position);
//				}
//			} else if (idtype.equals("mtalkid")) {
//				community = GroupActivity.list.get(position);
//			}
			if (idtype.equals("mtalkid")) {
				community = GroupActivity.list.get(position);
			} else {
				if (person == null) {
					community = CommunityFragment.list.get(position);
				} else {
					community = MessageListActivity.list.get(position);
				}
			}
			
		}
		coList = new ArrayList<Comment>();
		adapter = new ReplyListAdapter(context, coList);
		listView.setAdapter(adapter);
		if (!isAppend) {                                             //是否为附件内容
			if (isFromReceive || isFromNotice) {                     //来自推送或者通知列表或者未读消息列表
			    detail = new DetailTask().execute();
		    } else {	
			    initDetail();
		    }
		} else {
			detail = new DetailTask().execute();
		}

		if (isReply) {
			getWindow()
					.setSoftInputMode(
							WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
									| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		}
		
		if (isReplyList || isReply) {
			listView.setSelection(1);
		}
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(context, SpaceActivity.class);
				intent.putExtra("uid", coList.get(arg2 - 1).getAuthoruid());
				startActivity(intent);
			}
		});
	}
	
	

	
	

	private void initDetail() {
		initHeader(community.getTag());
		int len = AndroidUtil.dpToPx(48, context);
		imageLoader.DisplayImage(community.getAvatar(), avatar, 0, len, len);
		avatar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(context, SpaceActivity.class);
				intent.putExtra("uid", community.getUid());
				startActivity(intent);
			}
		});
		if (community.getVerifyType() != null) {
			verifyType.setBackgroundResource(DataService
					.getVerifyTypeRes(community.getVerifyType()));
		}
		name.setText(community.getName());
		if (!community.getTitle().equals("")) {
			title.setText(Html.fromHtml(community.getTitle(), getter, null));
			title.setVisibility(View.VISIBLE);
		} else {
			title.setVisibility(View.GONE);
		}
//		if (idtype.equals("talkid")) {
//			if (isAppend || isFromReceive || isFromNotice) {
//				content.setText(Html.fromHtml(community.getMessage(), getter,
//						null));
//			} else {
//				content.setText(Html.fromHtml(community.getContent(), getter,
//						null));
//			}
//		} else if (idtype.equals("mtalkid")) {
//			content.setText(Html.fromHtml(community.getMessage(), getter, null));
//		}
		if (idtype.equals("mtalkid")) {
			content.setText(Html.fromHtml(community.getMessage(), getter, null));
		} else {
			if (isAppend || isFromReceive || isFromNotice) {
				content.setText(Html.fromHtml(community.getMessage(), getter,
						null));
			} else {
				content.setText(Html.fromHtml(community.getContent(), getter,
						null));
			}
		} 

		time.setText(FuncUtil.timeToText(Long.valueOf(community.getDateline()) * 1000));

		// 附件内容
		View appendLayout = findViewById(R.id.append_layout);
		if (!community.getAppend_idtype().equals("")) {
			TextView appendName = (TextView) findViewById(R.id.append_name);
			TextView appendTitle = (TextView) findViewById(R.id.append_title);
			TextView appendText = (TextView) findViewById(R.id.append_text);
			appendName.setText("@" + community.getAppend_name());
			if (!community.getAppend_title().equals("")) {
				appendTitle.setText(community.getAppend_title());
				appendTitle.setVisibility(View.VISIBLE);
			} else {
				appendTitle.setVisibility(View.GONE);
			}
			appendText.setText(Html.fromHtml(community.getAppend_text(),
					getter, null));
			ImageView appendImage = (ImageView) findViewById(R.id.append_image);
			if (community.getAppend_image().equals("")) {
				appendImage.setVisibility(View.GONE);
			} else {
				imageLoader.DisplayImage(community.getAppend_image(), 0, 0,
					appendImage, new onLoadingFinishListener() {
						@Override
						public void onFinish(Bitmap bitmap,
								ImageView imageView, List<View> list) {
							if (bitmap != null) {
								float h = bitmap.getHeight();
								float w = bitmap.getWidth();
								RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView
										.getLayoutParams();
								float windowWidth = getWindowManager()
										.getDefaultDisplay().getWidth()
										- AndroidUtil.dpToPx(16, context) * 4;
								layoutParams.width = (int) windowWidth;
								layoutParams.height = (int) (h / w * windowWidth);
								imageView.setImageBitmap(bitmap);
								imageView.setLayoutParams(layoutParams);
							}
						}
					}, null, 0);
			}
			
			appendLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (idtype.equals("talkid") || idtype.equals("mtalkid")) {
						Intent intent = new Intent(context, ContentActivity.class);
						intent.putExtra("isReply", false);
						if (person == null) {
							intent.putExtra("position", position);
						}
						intent.putExtra("id", community.getAppend_id());
						intent.putExtra("idtype", idtype);
						intent.putExtra("isAppend", true);
	//					intent.putExtra("isFromReceive", isFromReceive);
						
						context.startActivity(intent);
					} else {
						Intent intent = new Intent(context,
								BrowserActivity.class);
						intent.putExtra("url", BaseService.DOMAIN
							+ community.getAppend_link());
						intent.putExtra("idtype", "feed");
						context.startActivity(intent);
					}
					
				}
			});
			appendLayout.setVisibility(View.VISIBLE);
		} else {
			appendLayout.setVisibility(View.GONE);
		}

		// 图片内容
		final JsonArray iArray = community.getImages();
		int size = iArray.size();
		for (int i = 0; i < imagesID.length; i++) {
			ImageView imageView = (ImageView) findViewById(imagesID[i]);
			if (size > i) {
				final JsonObject object = iArray.get(i).getAsJsonObject();
				imageLoader.DisplayImage(object.getAsJsonObject()
						.getAsJsonPrimitive("big").getAsString(), 0, 0,
						imageView, new onLoadingFinishListener() {
							@Override
							public void onFinish(Bitmap bitmap,
									ImageView imageView, List<View> list) {
								if (bitmap != null) {
									float h = bitmap.getHeight();
									float w = bitmap.getWidth();
									LayoutParams layoutParams = (LayoutParams) imageView
											.getLayoutParams();
									float windowWidth = getWindowManager()
											.getDefaultDisplay().getWidth()
											- AndroidUtil.dpToPx(16, context)
											* 2;
									layoutParams.width = (int) windowWidth;
									layoutParams.height = (int) (h / w * windowWidth);
									imageView.setImageBitmap(bitmap);
									imageView.setLayoutParams(layoutParams);
								}
							}
						}, null, 0);

				imageView.setTag(i);
				imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context,
								ViewImageActivity.class);
						intent.putExtra("path",
								BaseService.JsonArrayToStrings(iArray));
						intent.putExtra("position", (Integer) v.getTag());
						context.startActivity(intent);
					}
				});
				imageView.setVisibility(View.VISIBLE);
			} else {
				imageView.setVisibility(View.GONE);
			}
		}

		initShowgood();
		task = new ListTask().execute();
	}

	void initShowgood() {
		if (community.getShowgood() != null) {
			JsonArray sgArray = community.getShowgood();
			if (sgArray.size() > 0) {
				StringBuffer sb = new StringBuffer();
				sb.append(" ");
				for (int i = 0; i < sgArray.size(); i++) {
					JsonObject object = sgArray.get(i).getAsJsonObject();
					if (!object.isJsonNull()) {
						JsonElement element = object.get("name");
						if (!element.isJsonNull()) {
							sb.append(element.getAsJsonPrimitive()
									.getAsString());
							if (i < sgArray.size() - 1) {
								sb.append(",");
							}
						}
					}
				}
				showgood.setText(sb.toString());
			} else {
				showgood.setText(" 快来赞一个");
			}
			if (community.getIsshowgood() == 1) {
				goodButton.setSelected(true);
			} else {
				goodButton.setSelected(false);
			}
		}
	}

	class DetailTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
			    if (idtype.equals("mtalkid")) {
			//		community = SpaceService.mtalk(community.getAppend_id());
					community = SpaceService.mtalk(id);
				} else if (idtype.equals("talkid")) {
			//		community = SpaceService.talk(community.getAppend_id());
					community = SpaceService.talk(id);
				}
				
				if (isFromReceive) {
					count = SpaceService.noticecount() + CpService.pmcount();
				}
			} catch (MyHttpException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (community != null) {
				initDetail();
			}
			hideProgressDialog();
			super.onPostExecute(result);
		}
	}

	class GoodTask extends AsyncTask<Object, Void, String> {
		Community comm;
		JsonObject object;

		@Override
		protected String doInBackground(Object... params) {
			try {
				String result = "";
				comm = (Community) params[0];
				result = DoService.makeshowgood(comm.getId(), idtype);
				object = DoService.showgoodToplist(comm.getId(),
						idtype, "", "");
				return result;
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			if (object != null) {
				comm.setShowgood(object.get("showgoods").getAsJsonArray());
				comm.setIsshowgood(object.get("isshowgood").getAsInt());
				initShowgood();
			}
			showMessage(result);
			super.onPostExecute(result);
		}
	}

	class ListTask extends AsyncTask<Void, Void, String> {
		List<Comment> aList;

		@Override
		protected void onPreExecute() {
			if(flag == 0){
				showProgressDialog("正在加载中...");
			}else {
				
				page = page + 1;
			}
			isLoading = true;
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... arg0) {
			try {
				if (idtype.equals("mtalkid")) {
					aList = SpaceService.comment(community.getId(), idtype, page + "", "", "", "");
				} else {
					aList = SpaceService.comment(community.getId(), community.getIdtype(), page + "", "", "", "");
				}
				
//				if (isFromReceive) {
//				    aList = SpaceService.comment(id, idtype, page + "", "", "", "");
//				} else {
//				    aList = SpaceService.comment(community.getId(), idtype, page + "", "", "", "");
//				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			isLoading = false;
			if (flag == 0) {
				hideProgressDialog(); 
			}
			if (result == null) {
				if (aList.size() > 0 && aList != null) {
					if (flag == 0) {
						adapter = new ReplyListAdapter(context, aList);
						listView.addFooterView(footerView.getFooter());
						listView.setAdapter(adapter);
				    	listView.setOnScrollListener(new ScrollListener());
						coList = aList;	
					} else {
						coList.addAll(aList);
						adapter.notifyDataSetChanged();
					} 
			     } else if (aList != null){
//		    		if (flag == 0) {
//						listView.addFooterView(footerView.getFooter());
//					}
//					footerView.showNoData();
			    	 footerView.hideAll();
			     } 
			} else {
				showMessage(result);
			}
			flag = 1;
			super.onPostExecute(result);
		}
	}
	
	 private class ScrollListener implements OnScrollListener
	{
		private int listViewLastItem = 0;
		private boolean isOver = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			if (adapter.getCount() % page > 0 || adapter.getCount() == 0)
			{
				footerView.hideAll();
				isOver = true;
			}
			listViewLastItem = firstVisibleItem + visibleItemCount - 1; 
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{    
			if (!isOver && !isLoading && listViewLastItem >= adapter.getCount()-5 //&&adapter.getCount() > 8
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				footerView.showLoading();
				task = new ListTask().execute();
			}

		}
	}

	class CommentTask extends AsyncTask<String, Void, String> {
//		Comment comment;
//		String text;
//		public CommentTask(String text) {
//			this.text = text;
//		}
		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后..");
//			if (coList != null) {
//				comment = new Comment();
//				long dataline = new Date().getTime()/1000L;
//				comment.setDateline(String.valueOf(dataline));
//				comment.setMessage(text);
//				comment.setAuthorname(CacheService.getSpace().getUsername());
//			}
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
		//		String cid = community.getId();
				CpService.comment(community.getId(), idtype, params[0]);
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result != null) {
				showMessage(result);
			} else {
				page = 0;
			    coList.clear();
				task = new ListTask().execute();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == returnButton) {
			if (isFromReceive) {
				if (count == 1) {
					Intent intent = new Intent(context, IndexActivity.class);
					intent.putExtra("isFromReceive", true);
					context.startActivity(intent);
					 overridePendingTransition(R.anim.push_left_in,R.anim.push_right_out);
			    } else if (count > 1) {
				   Intent intent = new Intent(context, MsgListActivity.class);				  
				   context.startActivity(intent);
				   overridePendingTransition(R.anim.push_left_in,R.anim.push_right_out);
			    } 

				
			} 
			ContentActivity.this.finish();
		} else if (v == forwardButton) {
			if (!checkLogin()) {
				return;
			} else {
				showSharePopupWindow();
			}
		} else if (v == commentButton) {
			if (checkLogin()) {
				comment();
			}
		} else if (v == goodButton) {
			if (checkLogin()) {
				good = new GoodTask().execute(community);
			}
		}
	}
	
	public void showSharePopupWindow() {
		if (mPopupWindow == null) {
			View popupView = LayoutInflater.from(this).inflate(R.layout.popup_win_share, null);   
	        mPopupWindow = new PopupWindow(popupView,
	        		LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
	        mPopupWindow.setAnimationStyle(R.style.AnimationPreview);
			// 使其聚集  
			mPopupWindow.setFocusable(true);  
			// 设置允许在外点击消失  
			mPopupWindow.setOutsideTouchable(true);  
			// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景  
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); 
			
			Button btnBtnSinaWB = (Button) popupView.findViewById( R.id.btnSinaWB );
			Button btnBtnWXFriendCircle = (Button) popupView.findViewById( R.id.btnWXFriendCircle );
			Button btnBtnCancle = (Button) popupView.findViewById( R.id.btnCancle );
			Button btnLifeCircle = (Button)popupView.findViewById(R.id.btnLifeCircle);
			btnLifeCircle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					life();
					mPopupWindow.dismiss();
				}
			});
			
			btnBtnWXFriendCircle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					shareWxCircle();
					mPopupWindow.dismiss();
				}
			});
			btnBtnSinaWB.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
					if (!weibo.isValid()) {
						 weibo.setPlatformActionListener(new PlatformActionListener() {

							public void onComplete(Platform plat, int action,
									HashMap<String, Object> res) {
								Message msg = new Message();
								msg.arg1 = 1;
								msg.arg2 = action;
								msg.obj = plat;
								UIHandler.sendMessage(msg, ContentActivity.this);
							}

							public void onError(Platform plat, int action, Throwable t) {
								t.printStackTrace();

								Message msg = new Message();
								msg.arg1 = 2;
								msg.arg2 = action;
								msg.obj = plat;
								UIHandler.sendMessage(msg, ContentActivity.this);
							}
							
							public void onCancel(Platform plat, int action) {
								Message msg = new Message();
								msg.arg1 = 3;
								msg.arg2 = action;
								msg.obj = plat;
								weibo.removeAccount();
								UIHandler.sendMessage(msg, ContentActivity.this);
							}
						});
						weibo.authorize();
					} else {
						shareSinaWeibo();
					}
					mPopupWindow.dismiss();
				}
			});
			
			btnBtnCancle.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mPopupWindow.dismiss();
				}
			});
		}
		mPopupWindow.showAtLocation(listView, Gravity.BOTTOM, 0, 0);	
	}
	public void shareWxCircle() {
//		WechatMoments.ShareParams sp2 = new WechatMoments.ShareParams();
//		sp2.shareType = Platform.SHARE_TEXT;
//		if (community.getImages().size() > 0) {
//			sp2.imageUrl = community.getImages().get(0).getAsJsonObject()
//					.get("big").getAsString();
//		}
//		sp2.title = community.getTitle();
//		sp2.text = community.getMessage();
//		sp2.url = community.getShare_url();
//		Platform weibo2 = ShareSDK.getPlatform(context, WechatMoments.NAME);
//		weibo2.setPlatformActionListener(new CustomActionListener());
//		weibo2.share(sp2);
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = "http://test.lifeq.com.cn/";
		String wxTitle = title.getText().toString();
		String wxText = content.getText().toString();
//		System.out.println("=======wxTitle=====" + wxTitle);
//		System.out.println("=======wxText=====" + wxText);
		if (wxTitle.length() > 15) {
			wxTitle = wxTitle.substring(0, 14);
		}
		if (wxText.getBytes().length > 1000) {
			wxText = wxText.substring(0, (wxText.length()/2<500)?wxText.length()/2+1:499);
		}
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "" + wxText;
		msg.description ="" + wxText;
//		if (files.size() > 0) {
//			String imagePath = files.get(0).getPath().toString();
//			Bitmap bmp = BitmapFactory.decodeFile(imagePath);
//			Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
//			bmp.recycle();
//			if (thumbBmp != null) {
//				msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
//			} else {
//				Bitmap defaultBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//				msg.thumbData = Util.bmpToByteArray(defaultBmp, true);
//			}
//			
//		} else {
			Bitmap defaultBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
			msg.thumbData = Util.bmpToByteArray(defaultBmp, true);
//		}
		
		// 构造一个Req
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = "webpage" + String.valueOf(System.currentTimeMillis()); // transaction字段用于唯一标识一个请求
		req.message = msg;
		req.scene = SendMessageToWX.Req.WXSceneTimeline;
		
		// 调用api接口发送数据到微信
		api.sendReq(req);
	}
	public void shareSinaWeibo() {
//		Platform.ShareParams sp = new SinaWeibo.ShareParams();
//		sp.text = "[" + title.getText().toString() + "]" + content.getText().toString();
//		System.out.println("=======text=====" + "[" + title.getText().toString() + "]" + content.getText().toString());
//		sp.imagePath = community.getImages().get(0).getAsJsonObject().get("big").getAsString();
//		Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
//		weibo.SSOSetting(true);
//		weibo.share(sp);
		ShareParams sp = new ShareParams();
		sp.setText(content.getText().toString());
		if (community.getImages().size() > 0) {
		     Bitmap bitmap = null;
			try {
				bitmap = FuncUtil.getHttpBitmap(community.getImages().get(0).getAsJsonObject().get("big").getAsString());
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			System.out.println("=====size==>" + bitmap.getHeight());
//			System.out.println("===== System.currentTimeMillis()==>" +  System.currentTimeMillis());
            File file = PhotoUtil.saveBitmap(bitmap,PhotoUtil.getPhotoPath(context) + "/"+ System.currentTimeMillis() + ".png");
//			System.out.println("=====file==>" + file.getPath());
            sp.setImagePath(file.getPath().toString());	
		}
		
		Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
//		weibo.setPlatformActionListener(paListener); // 设置分享事件回调
		// 执行图文分享
		weibo.SSOSetting(true);
		weibo.share(sp);
	}
	public boolean handleMessage(Message msg) {
		Platform plat = (Platform) msg.obj;
		String text =LoginActivity.actionToString(msg.arg2);
		switch (msg.arg1) {
			case 1: 
				// 成功
				text = plat.getName() + " completed at " + text;
			   showMessage(text);
				shareSinaWeibo();
			    break;			
			case 2: {
				// 成功
//				text = plat.getName() + " caught error at " + text;
//				showMessage(text);
				return false;
			}				
			case 3: {
				// 取消
				text = plat.getName() + " canceled at " + text;
			//	Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
				showMessage(text);
				return false;
			}
		}

	
		return false;
	}

//	class CustomActionListener implements PlatformActionListener {
//		@Override
//		public void onCancel(Platform arg0, int arg1) {
//			UIUtil.toast((Activity) context,
//					context.getString(R.string.share_canceled));
//		}
//
//		@Override
//		public void onComplete(Platform arg0, int arg1,
//				HashMap<String, Object> arg2) {
//			UIUtil.toast((Activity) context,
//					context.getString(R.string.share_completed));
//		}
//
//		@Override
//		public void onError(Platform arg0, int arg1, Throwable arg2) {
//			UIUtil.toast((Activity) context,
//					context.getString(R.string.share_failed));
//			arg2.printStackTrace();
//		}
//	}


	void life() {
		Intent intent = new Intent(context, PostActivity.class);
		if (community.getIdtype() != null) {
			intent.putExtra("id", community.getId());
			intent.putExtra("text", content.getText().toString());
			intent.putExtra("avatar", community.getAvatar());
			intent.putExtra("idtype", community.getIdtype());
		} else {
			intent.putExtra("id", community.getMtalkid());
			intent.putExtra("idtype", "mtalkid");
		}
		if (community.getImages().size() > 0) {
			intent.putExtra("image", community.getImages().get(0)
					.getAsJsonObject().getAsJsonPrimitive("small")
					.getAsString());
		}
		intent.putExtra("name", community.getName());
		intent.putExtra("title", community.getTitle());
		startActivity(intent);
	}

	private void comment() {
		String text = editText.getEditableText().toString();
		if (text.equals("")) {
			return;
		}
		editText.setText("");
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		comment = new CommentTask().execute(text);
	}
}
